<?php
# Copyright © 2017 Nichlas Severinsen
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

session_start();

$config = include('config/config.php');

$db = new PDO(
  'mysql:host='.$config['hostname'].';dbname='.$config['database'],
  $config['username'],
  $config['password']);

?>

<html lang = "en">
  <head>
    <title>OB2 | Login</title>
    <link href="chota.min.css" rel="stylesheet">
  </head>
  <body>
    </br>
    <div class="row is-center">
      <div class="col-3">
        <div class="card">
          <div class = "container form-signin">
            <?php

            $login_failed = '';

            if(isset($_COOKIE['session_key']) && isset($_COOKIE['username'])){
              $sql = $db->prepare("SELECT username FROM user WHERE session_key=?");
              $sql->execute(array($_COOKIE['session_key']));
              $row = $sql->fetch(PDO::FETCH_ASSOC);
              if($row['username'] === $_COOKIE['username']){
                header("Location: /index.php");
              }
            }
            
            if (isset($_POST['login']) && 
                !empty($_POST['username']) && 
                !empty($_POST['password'])) {

              #$statement = $pdo->query("SELECT password FROM user");
              #$row = $statement->fetch(PDO::FETCH_ASSOC);
              $sql = $db->prepare("SELECT password FROM user WHERE username=?");
              $sql->execute(array($_POST['username']));
              $rows = $sql->fetch(PDO::FETCH_ASSOC);


              # Compatibility login with old setup
              if(md5($_POST['password']) === $rows['password']){
                $session_key = password_hash(random_int(PHP_INT_MIN, PHP_INT_MAX), PASSWORD_DEFAULT);

                # Make sure database schema is up to date
                $sql = $db->exec("ALTER TABLE user MODIFY password VARCHAR(60) BINARY");
                $sql = $db->exec("ALTER TABLE user ADD COLUMN session_key VARCHAR(60) BINARY");

                # Set session key in database, also replace md5 with bcrypt
                $sql = $db->prepare("UPDATE user SET session_key=?, password=? WHERE username=?");
                $sql->execute(array($session_key, password_hash($_POST['password'], PASSWORD_DEFAULT ), $_POST['username']));

                $_SESSION['username'] = $_POST['username'];
                $_SESSION['session_key'] = $session_key;
                
                if(isset($_POST['remember'])){ 
                  if($_POST['remember'] === "on"){
                    setcookie('username', $_POST['username'], time() +2592000);
                    setcookie('session_key',$session_key, time() +2592000);
                  }
                }

                header("Location: /index.php");
              }
              
              # New secure login
              if(password_verify($_POST['password'], $rows['password'])){
                $session_key = password_hash(random_int(PHP_INT_MIN, PHP_INT_MAX), PASSWORD_DEFAULT);

                # Set session key in database, also replace md5 with bcrypt
                $sql = $db->prepare("UPDATE user SET session_key=? WHERE username=?");
                $sql->execute(array($session_key, $_POST['username']));

                $_SESSION['username'] = $_POST['username'];        
                $_SESSION['session_key'] = $session_key;

                if(isset($_POST['remember'])){ 
                  if($_POST['remember'] === "on"){
                    setcookie('username', $_POST['username'], time() +2592000);
                    setcookie('session_key',$session_key, time() +2592000);
                  }
                }

                header("Location: ./index.php");
              }
                
              $login_failed = '
              <p class = "is-center">
                Wrong username or password
              </p>';
             
            }
            
            ?>
          </div>
          <div class = "container">
            <form role = "form" action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method = "post">
              </br>
              <p>
                <input type = "text" name = "username" placeholder = "username" required autofocus>
              </p>
              <p>
                <input type = "password" name = "password" placeholder = "password" required>
              </p>
              <p>
                <button class = "btn btn-lg btn-primary btn-block is-full-width" type = "submit" name = "login">Login</button>
              </p>
              <p class = "is-center">
                <label for="checkbox3"><input type="checkbox" name="remember" >Remember me for 30 days</label>
              </p>
              <?php echo $login_failed; ?>
            </form>  
          </div> 
        </div>
      </div>
    </div>
  </body>
</html>

